<!--
 * @Author: RAY_HUI 1541917867@qq.com
 * @Date: 2025-07-07 10:24:24
 * @LastEditors: RAY_HUI 1541917867@qq.com
 * @LastEditTime: 2025-08-04 16:53:00
 * @FilePath: \website-reconstruction---vue\src\components\sections\home\ProductCategories.vue
 * @Description: 
 * 
 * Copyright (c) 2025 by ${git_name_email}, All Rights Reserved. 
-->
<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { getProductTypeNum } from '@/api/xyybackend/getVoList.js'
import { Category, DataProp } from '@/types/selfdefine/Layout'
import { getRandomAnimation } from '@/utils/tools/tools'
import { useLangStore } from '@/stores/langStore'

// ✅ 1. 定义 props（放在最上面）
const props = defineProps<{
  data: DataProp | undefined
}>()

// ✅ 2. 使用 router
const router = useRouter()

// ✅ 3. 使用 langStore（不要解构！）
const langStore = useLangStore()

// ✅ 4. 存储异步数据：partId → count
const typeCounts = ref<Record<number, number>>({})

// ✅ 5. 存储动画：partId → animation（避免每次 computed 都变）
const categoryAnimations = ref<Record<number, string>>({})

// ✅ 6. 异步获取 count 数据
onMounted(async () => {
  if (!props.data?.partContentVoList?.length) return

  try {
    const res = await getProductTypeNum()

    if (!Array.isArray(res.rows)) {
      console.error('res.rows 不是一个数组！')
      return
    }

    // 假设 res.rows 与 partContentVoList 按索引对应
    props.data.partContentVoList.forEach((item, index) => {
      const row = res.rows[index]
      typeCounts.value[item.partId] = row?.count ?? 0
      // ✅ 只生成一次动画
      categoryAnimations.value[item.partId] = getRandomAnimation()
    })
  } catch (err) {
    console.error('获取产品数量失败:', err)
  }
})

// ✅ 7. computed：响应式生成 categories
const categories = computed(() => {
  // 如果 props.data 不存在，返回空数组
  if (!props.data?.partContentVoList) return []

  return props.data.partContentVoList.map((item) => {
    return {
      partId: item.partId,
      imageUrl: item.imageUrl,
      title: item.content, // 如果 content 本身是多语言字段，可在此切换
      count: typeCounts.value[item.partId] ?? 0,
      delay: '0.3s',
      animation: categoryAnimations.value[item.partId] ?? 'fadeInUp', // fallback
    } satisfies Category // 类型校验
  })
})

// ✅ 8. 方法
const goToCategory = (route?: string) => {
  if (route) {
    router.push(route)
  }
}
//类别
const typeString = computed(() => {
  const isZh = langStore.currentLang === 'zh'
  return {
    typeName: isZh ? '种' : 'types',
  }
})
</script>

<template>
  <section class="main-section categories-view1-full">
    <span class="light-transparent"></span>
    <div class="container" v-if="data.partTitle">
      <div class="section-header text-center">
        <div class="section-heading">
          <h3 class="text-custom-white">
            {{ data.partTitle.slice(0, 2) }}
            <span class="text-yellow">{{ data.partTitle.slice(2) }}</span>
          </h3>
          <div class="section-description">
            <p class="text-custom-white">
              {{ data.content }}
            </p>
          </div>
        </div>
      </div>
      <div class="row">
        <div class="col-md-12">
          <!-- Categories List -->
          <div class="categories-1 categories-view1">
            <ul class="row">
              <li
                v-for="category in categories"
                :key="category.partId"
                class="col-lg-4 col-md-6"
                :class="`wow ${category.animation}`"
                :data-wow-delay="category.delay"
              >
                <a href="#" @click.prevent="goToCategory()">
                  <div class="categories-view1-wrap">
                    <img
                      :src="category.imageUrl"
                      alt=""
                      style="max-width: 100%; height: auto"
                    />
                    <h6>{{ category.title }}</h6>
                    <small
                      >({{ category.count }}{{ typeString.typeName }})</small
                    >
                  </div>
                </a>
              </li>
            </ul>
          </div>
        </div>
      </div>
    </div>
  </section>
</template>
